3. How to Control Flows - if-else, loops; Something more

  1. Flows?
    • In Chapter 2, we learned only the sequential flow. Our programs are like a sequence of mostly assignment statements and print statements.
    • Let's read an age value from the user. What if we want to print "Young" when the age is less than or equal to 60. Otherwise we want to print "Old". How can we make this program?
    • We need to know how to check whether the age is less than or equal to 60. How?
    • A little bit more. How to evaluate a Boolean expression?
  2. Boolean expressions
    • What are the two Boolean values?
    • Only two values: True and False; not true nor TRUE
    • Let's try a = True; b = false. How to fix it?
    • Let's try True = "Is it okay?". How to fix it?
    • What kind of comparison operators? E.g., how to check if age is less than or equal to 20?
      • ==    equal to
      • !=    not equal to
      • >    greater than
      • >=    greater than or equal to
      • <    less than
      • <=    less than or equal to
      • Let's try the next example with the console.
        age = 21
        age == 40
        age < 40
        age <= 41
        age > 40
        age >= 40
        
    • What kind of boolean operators? How to combine True and False values, i.e., comparison operations?
      • not
      • and
      • or
      • Do we remember the truth tables?
      • Let's try the next example with the concole.
        age = 21
        age <= 16 or age > 35  # What value?
        (age > 16) and (age <= 35)  # ???
        not age > 35  # ???
        
      • Comparison operators have higher precedences than boolean operators.
    • Boolean expressions are also called conditions in flow control statements that control the excution of statements.
    • A question. What if we want to print 'Young' if age is less than 35, i.e., if age < 35?
  3. if-elif-else statements
    • if condition:
          statement or statements    # There should be an indentation before a statement or indentaitons before statements.
      
    • Let's try the next example.
      age = 21
      if age < 35:
          print("Young")
          print(age)
      
    • Tic-tac-toe game and 3×3 puzzle game - Let's try the next example.
      row = ???(input("Enter the row number: ")  # Integer 0, 1, or 2 is expected.
      if row < 0 ??? row > 2:
          print("Wrong row number")
      else
          print("Correct row number")
      
    • Let's try the next example. What will be printed?
      age = 40
      if age < 35:
          print("Young")
          print(age)
      else:
          print("Not young anymore")
      
    • The group of statements with an indentation is called a block. With the indentation, we can easily see to what the block belong. In the above example, two statements print("Young"); print(age) belong to if age < 35:.
    • Let's try the next example. What will be printed? Does print(age) belong to if age < 35:?
      age = 40
      if age < 35:
          print("Young")
      print(age)
      
    • A block can include other blocks, even another if-else. Let's try the next example. Any error? How to fix?
      age = input("Age: ")
      if age >= 20:
          if age >= 60:
              print("Well aged");
          else:
              print("Adult")
      else:
          print("Teenager, or")
          print("Kid")
      
    • elif can used for else:\n if. Let's try the next example. What will be printed? Anything wrong? How to fix it?
      age = input("Age: ")
      name = ???("Name: ")
      
      if name == "John" and age == 20:
          print("John Doe")
      else:
          if name == 'John' ??? age == 25:
              print("John Gilbert")
          else:
              print("Who are you?")
              
      if name == "John" and age == 20:
          print("John Doe")
      elif name == 'John' ??? age == 25:
          print("John Gilbert")
      else???
          print("Who are you?")
      
  4. while loop statements
    • Exercise problem - What if we want to read 20 numbers and find the average?
      • Let's think about the agorithm that reads numbers and finds the average. Any good idear?
        Repeat 20 times the followings:
            Read a number
            Add the number to a variable
        Divide the variable by 20
        Print the result
        
      • The repeatition of a block is called a loop.
      • A question is how to repeat the loop 20 times. Any good idea? Here is a more detail algorithm.
        count = 0
        Repeat the followings while count < 20:
            Read a number
            Add the number to a variable
            Increase count by 1
        Divide the variable by 20
        Print the result
        
      • How to read a number and add the number to a variable? How to increase the counter variable in the above algorithm?
        count = 0
        Repeat the followings while count < 20:
            number = Read a number
            sum = sum + number
            count = count + 1
        Divide the variable by 20
        Print the result
        
      • while loop statement
        while condition:
            ...
        
      • Let's write the correct code for the above algorithm to find the average.
        count = ???
        sum = ???
        while count < 20:
            number = input("Enter a number: ")
            sum = sum + number
            count = count + 1
        average = sum / 20
        print("Average = " + average);
        
      • Let's try the above code. Anthing wrong? How to fix?
    • Exercise problem - What if we want to count numbers, 1, 2, 3, ...? But the code needs to ask the user if the user wants to continue.
      • Can we write an algorithm to solve the above problem?
        While the user wants to keep playing, repeat the followings:
            Print the value;
            Increase the value;
        
      • What to do with "While the user wants to keep playing"?
        While answer is 'yes', repeat the followings:
            Print the value
            Increase the value
            answer = input("Continue? ")
        
      • Let's write the code for the above algorithm.
        ????
        while answer == 'yes':
            print(value)
            value = value + 1
            answer = input("Continue? ")
        
      • Let's try the above code. Anthing wrong? How to fix?
    • Exercise problem - What if we want to read numbers until the user enters a negative number, and compute the sum and print it?
      • Let's write an algorithm to solve the above problem.
        Repeat the followings forever:    # forever? how?
            If the user enters a negative value:    # how?
                break the loop    # how?
            Add the value into sum    # how?
        Print the sum
        
      • Let's write the code for the above algorithm. We need to know how to break out a loop when the input is negative.
        ????
        while True:  # called infinite loop
            value = input("Enter a value: ")
            If value < 0:
                break    # the break statement to exit out of a loop
            sum = sum + value
        print("The sum is " + sum)
        
      • Let's try the above code. Anthing wrong? How to fix?
    • Exercise problem - In a loop, let's read password phrases. If the length of the password phrase is less than 5, then skip to the next password pharase. Otherwise, print the password phrase. If 5 password phrases of length >= 5 are read, then stop the loop.
      • Let's write an algorithm to solve the above problem. We need to think there can be short password phrases.
        Repeat the followings forever:    # how?
            password <- Read a password phrase
            If the length of password < 5:
                Skip to the next password    # how?
            Print password
            count = count + 1
            if count >= 5:
                Stop the loop    # how?
        
      • Let's write the code for the above algorithm. You need to know how to skip the loop to the next iteration.
        ????
        while True:
            password = input("Enter a password: ")
            if len(password) < 5:
                print("Too short password phrase")
                continue    # the continue statement to the next iteration of a loop
            print(password)
            count = count + 1
            if count >= 5:
                break    # the break statement to exit out of a loop
        
      • Let's try the above code. Anthing wrong? How to fix?
    • Tic-tac-toe game and 3×3 puzzle game - When the user selects the next move, i,e., location of the game board, the user needs to enter a row value and a column value. What if the user enters an integer < 0 or > 2?
      • Ininite loop
      • If the user enters the correct row value, then the control needs to break out of the loop.
      • Let's write the code for the above algorithm.
        ????  # infinite loop
            row = int(input("Enter row number: "))
            if ????
                ????
        ????  # infinite loop
            column = int(input("Enter column number: "))
            if ????
                ????
        print(row)
        print(column)
        
  5. for loop statements
    • What if we want to execute a code block only a certain number of times? Can we use a while loop? Yes, but there is another more convenient loop statement.
    • Here is an exmple of a for loop. Let's try the code. What values are printed?
      for i in range(10):
          print(i)
      
    • The for statement with range(10) in the above example iterates 10 times. The variable i will have 0, 1, ..., 9.
    • Exercise problem - Write a program that adds numbers from 1 upto 1000.
      • Algorithm?
        Repeat the followings with i from 1 upto 1000:
            sum = sum + i
        Print sum
        
      • How to do with "Repeat the followings with i from 1 upto 1000"?
        for i in range(1001):    # 0, 1, 2, ..., 1000
        
      • Let's write the code for the above algorithm.
        for i in range(1001):
            sum = sum + i
        print(sum)
        
      • Let's try the above code. Anthing wrong? How to fix?
    • Exercise problem - Write a program that prints a string within the two '|' symbols. E.g., |Wonterful world!|.
      strww = 'What a wonderful world!'
      print('|', end='')
      for c in strww:  # for each character in strww
          print(c, end='')  # end='' makes the next character be printed in the same line.
      print('|')
      # another idea using string concatenation
      prtstr = ''
      prtstr = prtstr + '|'  # string concatenation
      for c in strww:  # for each character in strww
          prtstr = prtstr + c
      prtstr = prtstr + '|'
      print(prtstr)
      
    • We can convert a for loop statement to a while loop statement. Can we convert the code in the above exercise to use a while loop instead?
  6. range()
    • The function range() can have multiple arguments that are separated by commas.
    • Let's try range(10, 20). What values are printed?
    • range() can have three arguments.
      range(end)    # 0, ..., end-1
      range(start, end)    # start, start+1, ..., end-1
      range(start, end, step)    # start, start+step, ...
      
    • E.g.,
      range(10)    # 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
      range(3, 10)    # 3, 4, 5, 6, 7, 8, 9
      range(0, 10, 2)    # 0, 2, 4, 6, 8
      
    • range() can be used for negative numbers as well. See the next example.
      for i in range(10, -5, -2):    # 10, 8, 6, 4, 2, 0, -2, -4
          print(i)
      
    • How to add all the integers from 1000 upto 1000000 inclusively"? Let's try the next example.
      ????
      for i in range(????):
          ????
      print(sum)
      
  7. How to use the programs that were developed? How to import modules? E.g., random
    • We have used built-in functions - input(), print(), int(), float(), len(), range(), ... They are difined in a standard library that is automatically included (oac imported) in our programs. All the Python programs can use them.
    • Python programs can use modules. A module is a program that contains related functions that can be imported into our programs, so that our programs can use those functions. E.g., the math module includes mathematics-related functions.
    • Those modules should be imported first in our programs before the functions in those modules are used.
    • Here is an example of the random module. We may follow the link to see what functions are defined in the random module.
      import random
      for i in range(5):
          r = random.randint(0, 19)    # .randint() - a random integer in [0, 19] (or [0, 20))
          print(r)
      
    • One important programming convention is not to use existing module names for our variables and functions in our program. Otherwise, those overwritten modules cannot be used, because the names defined in our program have higher precedence. Let's try the next example.
      import random
      for random in range(5):
          r = random.randint(10, 100-1)
          print(r)
      
    • We can import multiple modules in one import statement. E.g.,
      import sys, os, random
      
    • The variant of import statement - from ... import .... We don't need to keep using the module name. E.g.,
      from random import *
      for i in range(5):
          r = randint(-10, 10)    # randint() is defined in random.
          print(r)
      for i in range(5):
          r = random()    # random() generates a random floats in [0, 1).
          print(r)
      for i in range(5):
          r = uniform(-5, 2.5)    # uniform(a, b) generates a random floats in [a, b).
          print(r)
      
  8. How to end a program early?
    • Sometime we will need to exit the program completely when a certain condition is satisfied. In this case we can use exit(). E.g.,
      import random
      for i in range(1000):
          r = random.randint(0, 20-1)
          if r == 0 or r == 1:
              exit()
          print(r)
      
  9. Programming exercises
    1. Write a program that reads a number grade and decides the final letter grade.
      • A: grade >= 90
      • B: grade >= 80
      • C: grade >= 70
      • D: grade >= 60
      • F: grade < 60
    2. Write a program that reads an integer and decides whether the integer is even.
    3. Write a program that reads numbers until the user enters a negative number and finds the largest.
    4. Write a program that reads the multiples of 3 from 0 upto 300 and finds the sum.
    5. Write a program that generates 100 random integers in [10, 100).
    6. Write a program that prints the sine values for 0, 1, 2, ..., 720 degrees. We may use the math module.
    7. Tic-tac-toe game
      • Write the code that decides random row value and column value. The row value column value should be in [0, 2].
      • Write a program that reads the row value and column value from the user. if they are not in [0, 2], then they have to be read again.
    8. 3×3 puzzle game
      • Write the code that decides random row value and column value. The row value column value should be in [0, 2].
      • Write the code that reads the row value and column value from the user. if they are not in [0, 2], then they have to be read again.
      • Write the code that print 8 random integers in [1, 8]. Can we write a program that prints 8 different random integers in [1, 8], i.e., a random sequence of 1, ..., 8?
      • Write the code that swaps two variables.
      • Write a program that decides a random direction, i.e., one of NORTH, SOUTH, EAST, and WEST. Hint - We can use random integer in [0, 3], or random.choice()
    9. 1-D Mine sweeper game
      • Write the code that decides random integer in [0, 20).
      • Write the code that prints a string in the way that all the characters are separated by '|'. E.g., |M|1|0|0|1|M|2|M|1|0| for "M1001M2M10".
  10. References